<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Target Details</title>
    <link href="resources/bootstrap.min.css" rel="stylesheet">
    <style>
        .title {
            text-align: center;
            margin: 20px 0;
            font-weight: bold;
        }
        .type-tabs {
            display: flex;
            justify-content: center;
            margin-bottom: 20px;
            flex-wrap: wrap;
        }
        .type-tab {
            padding: 8px 15px;
            margin: 0 5px 10px;
            cursor: pointer;
            border-radius: 4px;
            background-color: #f8f9fa;
            border: 1px solid #dee2e6;
        }
        .type-tab.active {
            background-color: #0d6efd;
            color: white;
            border-color: #0d6efd;
        }
        .light-curve-container {
            display: flex;
            justify-content: center;
            margin: 20px 0;
        }
        .light-curve-images {
            display: flex;
            justify-content: center;
            gap: 20px;
            max-width: 100%;
            margin: 0 auto;
        }
        .light-curve-image {
            flex: 1;
            text-align: center;
        }
        .light-curve-image img {
            max-width: 100%;
            height: auto;
            max-height: 500px;
            display: block;
            margin: 0 auto;
        }
        .identify-images-container {
            width: 100%;
            margin: 20px 0;
            text-align: center;
        }
        .identify-images-title {
            margin-bottom: 15px;
        }
        .band-comparison {
            display: flex;
            justify-content: center;
            gap: 20px;
            margin-bottom: 15px;
        }
        .band-image {
            width: 45%;
            border: 1px solid #ddd;
            border-radius: 5px;
            overflow: hidden;
        }
        .band-image img {
            width: 100%;
            height: auto;
            max-height: 400px;
            object-fit: contain;
        }
        .band-label {
            text-align: center;
            padding: 5px;
            background-color: #f8f9fa;
            border-bottom: 1px solid #ddd;
        }
        .slideshow-controls {
            display: flex;
            justify-content: center;
            gap: 10px;
            margin-top: 15px;
        }
        .control-btn {
            padding: 5px 15px;
            border: 1px solid #ddd;
            border-radius: 4px;
            background-color: #f8f9fa;
            cursor: pointer;
        }
        .control-btn:hover {
            background-color: #e9ecef;
        }
        .data-table {
            margin: 20px auto;
            width: 80%;
        }
        .back-link {
            display: block;
            margin: 20px 0;
            text-align: center;
        }
        .data-type-selector {
            text-align: center;
            margin: 15px 0;
            display: none;
        }
        .data-type-btn {
            margin: 0 10px;
            padding: 5px 15px;
            cursor: pointer;
            border-radius: 4px;
            background-color: #f8f9fa;
            border: 1px solid #dee2e6;
        }
        .data-type-btn.active {
            background-color: #0d6efd;
            color: white;
            border-color: #0d6efd;
        }
        .no-data {
            text-align: center;
            color: #6c757d;
            font-style: italic;
            margin: 20px 0;
        }
        .download-link {
            margin-left: 10px;
            font-size: 0.8em;
            font-weight: normal;
        }
        .pagination-controls {
            display: flex;
            justify-content: center;
            margin-top: 15px;
        }
        .page-info {
            margin: 0 15px;
            line-height: 35px;
        }
    </style>
</head>
<body>
    <div class="container">
        <a href="index.html" class="back-link">← Back to Target List</a>
        <h1 class="title" id="targetTitle">Target Details</h1>
        
        <div class="type-tabs" id="typeTabs" style="display: none;">
            <!-- 类型标签将在这里动态加载 -->
        </div>
        
        <div class="data-type-selector">
            <span class="data-type-btn" id="qlBtn">QuickLook</span>
            <span class="data-type-btn" id="rfBtn">Refined</span>
        </div>
        
        <div style="text-align: center;">
            <span style="font-size: 28px; display: none; text-align: center; margin-bottom: 20px;margin-right: 20px;">
                <a href="#" target="_blank" id="lightCurvePage">Click to Interact with the Light Curve</a>
            </span>
            <span style="font-size: 28px; display: none; text-align: center; margin-bottom: 20px;">
                <a href="#" target="_blank" id="lightCurveEvolutionImage">Show Color In Log Scale</a>
            </span>
        </div>
        <div class="light-curve-container">
            <div class="light-curve-images">
                <div class="light-curve-image">
                    <img id="lightCurveImage" src="" alt="Light Curve" style="display: none;">
                </div>
                <div class="light-curve-image">
                    <img id="lightCurveBRChange" src="" alt="Light Curve of Color Change" style="display: none;">
                </div>
            </div>
            <div id="noLightCurve" class="no-data" style="display: none; text-align: center;">No light curve image available</div>
        </div>
        
        <div class="identify-images-container">
            <h3 class="identify-images-title">Finding charts</h3>
            <div class="band-comparison" id="bandComparison">
                <div class="band-image">
                    <div class="band-label">B Band</div>
                    <img id="bBandImage" src="" alt="B Band Image">
                </div>
                <div class="band-image">
                    <div class="band-label">R Band</div>
                    <img id="rBandImage" src="" alt="R Band Image">
                </div>
            </div>
            <div class="slideshow-controls">
                <div class="control-btn" id="prevBtn">Previous</div>
                <div class="control-btn" id="playPauseBtn">Pause</div>
                <div class="control-btn" id="nextBtn">Next</div>
            </div>
            <div id="noIdentifyImages" class="no-data" style="display: none;">No identify images available</div>
            <div id="imageCounter" style="text-align: center; margin-top: 10px;"></div>
        </div>
        
        <div class="data-table">
            <h3 class="text-center">Log of photometries 
                <a href="#" id="downloadLink" class="download-link" style="display: none;" target="_blank">(Download)</a>
            </h3>
            <div class="table-responsive">
                <table class="table table-striped table-bordered" id="dataTable">
                    <!-- 数据将在这里动态加载 -->
                </table>
                <div id="noDataTable" class="no-data" style="display: none;">No light curve data available</div>
                <div class="pagination-controls" id="paginationControls" style="display: none;">
                    <button class="btn btn-sm btn-outline-primary" id="prevPageBtn">Previous</button>
                    <span class="page-info" id="pageInfo">Page 1 of 1</span>
                    <button class="btn btn-sm btn-outline-primary" id="nextPageBtn">Next</button>
                </div>
            </div>
        </div>
    </div>

    <script src="resources/bootstrap.bundle.min.js"></script>
    <script>
        // 定义根路径
        const rootUrl = '/vtepobjlist';
        let slideshowInterval;
        let currentImageIndex = 0;
        let isPlaying = true;
        let imagePairs = [];
        
        // 分页相关变量
        let currentPage = 1;
        const rowsPerPage = 10;
        let tableData = [];
        let sortedData = [];
        
        document.addEventListener('DOMContentLoaded', function() {
            // 从URL获取参数
            const urlParams = new URLSearchParams(window.location.search);
            const targetName = urlParams.get('name');
            const encodedTargetName = encodeURIComponent(targetName);
            let currentType = urlParams.get('type');
            let currentDataType = urlParams.get('dataType') || 'quicklook';
            
            if (!targetName) {
                window.location.href = 'index.html';
                return;
            }

            // 设置页面标题
            document.getElementById('targetTitle').textContent = `Target: ${targetName}`;
            
            // 设置数据类型按钮状态
            document.getElementById('qlBtn').classList.toggle('active', currentDataType === 'quicklook');
            document.getElementById('rfBtn').classList.toggle('active', currentDataType === 'refined');
            
            // 添加数据类型按钮事件
            document.getElementById('qlBtn').addEventListener('click', () => {
                currentDataType = 'quicklook';
                updateDataType();
            });
            
            document.getElementById('rfBtn').addEventListener('click', () => {
                currentDataType = 'refined';
                updateDataType();
            });
            
            // 添加控制按钮事件
            document.getElementById('prevBtn').addEventListener('click', showPreviousImage);
            document.getElementById('nextBtn').addEventListener('click', showNextImage);
            document.getElementById('playPauseBtn').addEventListener('click', togglePlayPause);
            
            // 添加分页按钮事件
            document.getElementById('prevPageBtn').addEventListener('click', () => {
                if (currentPage > 1) {
                    currentPage--;
                    renderDataTablePage();
                }
            });
            
            document.getElementById('nextPageBtn').addEventListener('click', () => {
                const totalPages = Math.ceil(sortedData.length / rowsPerPage);
                if (currentPage < totalPages) {
                    currentPage++;
                    renderDataTablePage();
                }
            });
            
            function updateDataType() {
                // 更新按钮状态
                document.getElementById('qlBtn').classList.toggle('active', currentDataType === 'quicklook');
                document.getElementById('rfBtn').classList.toggle('active', currentDataType === 'refined');
                
                // 重置分页
                currentPage = 1;
                
                // 重新加载数据
                loadTargetData();
            }

            // 获取目标数据
            fetch(`${rootUrl}/${encodedTargetName}`)
                .then(response => {
                    if (!response.ok) {
                        throw new Error('Network response was not ok');
                    }
                    return response.json();
                })
                .then(target => {
                    // 渲染类型标签
                    renderTypeTabs(target.obslist);
                    
                    // 如果没有指定类型或类型不存在，使用第一个类型
                    if (!currentType || !target.obslist.some(obs => obs.type === currentType)) {
                        currentType = target.obslist[0].type;
                    }
                    
                    // 加载目标数据
                    loadTargetData();
                    
                    // 添加类型标签点击事件
                    document.querySelectorAll('.type-tab').forEach(tab => {
                        tab.addEventListener('click', () => {
                            currentType = tab.dataset.type;
                            // 重置分页
                            currentPage = 1;
                            loadTargetData();
                            
                            // 更新标签状态
                            document.querySelectorAll('.type-tab').forEach(t => {
                                t.classList.toggle('active', t.dataset.type === currentType);
                            });
                        });
                    });
                })
                .catch(error => {
                    console.error('Error fetching target details:', error);
                    document.getElementById('noLightCurve').style.display = 'block';
                    document.getElementById('noIdentifyImages').style.display = 'block';
                    document.getElementById('noDataTable').style.display = 'block';
                });
                
            function renderTypeTabs(obslist) {
                const typeTabs = document.getElementById('typeTabs');
                typeTabs.innerHTML = '';
                
                // 按refined_date排序，最新的在前面
                const sortedObs = [...obslist].sort((a, b) => {
                    const dateA = a.refined_date ? new Date(a.refined_date) : 0;
                    const dateB = b.refined_date ? new Date(b.refined_date) : 0;
                    return dateB - dateA;
                });
                
                sortedObs.forEach(obs => {
                    const tab = document.createElement('div');
                    tab.className = `type-tab ${obs.type === currentType ? 'active' : ''}`;
                    tab.textContent = obs.type;
                    tab.dataset.type = obs.type;
                    typeTabs.appendChild(tab);
                });
            }
            
            function loadTargetData() {
                // 更新URL但不刷新页面
                const newUrl = `detail.html?name=${encodedTargetName}&type=${currentType}&dataType=${currentDataType}`;
                window.history.pushState({}, '', newUrl);
                
                // 清除之前的轮播定时器
                if (slideshowInterval) {
                    clearInterval(slideshowInterval);
                }
                
                // 获取目标数据
                fetch(`${rootUrl}/${encodedTargetName}`)
                    .then(response => {
                        if (!response.ok) {
                            throw new Error('Network response was not ok');
                        }
                        return response.json();
                    })
                    .then(target => {
                        // 找到当前类型的观测
                        const currentObs = target.obslist.find(obs => obs.type === currentType);
                        if (!currentObs) {
                            throw new Error('Observation type not found');
                        }
                        
                        // 显示/隐藏光变曲线图
                        const lightCurveImage = document.getElementById('lightCurveImage');
                        const lightCurveBRChange = document.getElementById('lightCurveBRChange');
                        const lightCurveEvolutionImage = document.getElementById('lightCurveEvolutionImage');
                        const lightCurvePage = document.getElementById('lightCurvePage');
                        const noLightCurve = document.getElementById('noLightCurve');
                        const imageSrc = currentDataType === 'quicklook' ? 
                            `${rootUrl}/files/${currentObs.quickLook.lightCurveImage}` : 
                            `${rootUrl}/files/${currentObs.refined.lightCurveImage}`;
                        
                        if (imageSrc && !imageSrc.includes('null')) {
                            lightCurveImage.src = imageSrc;
                            lightCurveImage.style.display = 'block';
                            noLightCurve.style.display = 'none';

                            lightCurvePage.href = imageSrc.replace('.png', '.html');

                            const lcImgName = targetName+".quicklook.png";
                            const lccImgName = "results/B-R_evolution.png";
                            lightCurveBRChange.src = imageSrc.replace(lcImgName, lccImgName);
                            lightCurveBRChange.style.display = 'block';

                            const lccImgNameLog = "results/B-R_evolution_log.png";
                            lightCurveEvolutionImage.href = imageSrc.replace(lcImgName, lccImgNameLog);
                        } else {
                            lightCurveImage.style.display = 'none';
                            noLightCurve.style.display = 'block';
                        }
                        
                        // 处理证认图
                        const noIdentifyImages = document.getElementById('noIdentifyImages');
                        const allImages = [
                            ...(currentObs.quickLook.identifyImages || []),
                            ...(currentObs.refined.identifyImages || [])
                        ].map(img => `${rootUrl}/files/${img}`);
                        
                        // 分组B和R波段的图像
                        imagePairs = groupBandImages(allImages);
                        
                        if (imagePairs.length > 0) {
                            currentImageIndex = 0;
                            updateBandImages();
                            noIdentifyImages.style.display = 'none';
                            
                            // 设置自动轮播
                            if (isPlaying) {
                                startSlideshow();
                            }
                        } else {
                            noIdentifyImages.style.display = 'block';
                        }
                        
                        // 显示/隐藏光变曲线数据
                        const dataTable = document.getElementById('dataTable');
                        const noDataTable = document.getElementById('noDataTable');
                        const dataFile = currentDataType === 'quicklook' ? 
                            `${rootUrl}/files/${currentObs.quickLook.lightCurveData}` : 
                            `${rootUrl}/files/${currentObs.refined.lightCurveData}`;
                        
                        if (dataFile && !dataFile.includes('null')) {
                            // 显示下载链接
                            const downloadLink = document.getElementById('downloadLink');
                            downloadLink.href = dataFile;
                            downloadLink.style.display = 'inline';
                            
                            fetch(dataFile)
                                .then(response => {
                                    if (!response.ok) {
                                        throw new Error('Failed to load data file');
                                    }
                                    return response.text();
                                })
                                .then(text => {
                                    const lines = text.split('\n').filter(line => line.trim() !== '');
                                    if (lines.length > 0) {
                                        // 假设是空格分隔的数据
                                        const headers = lines[0].split(/\s+/).filter(h => h);
                                        tableData = [];
                                        
                                        for (let i = 1; i < lines.length; i++) {
                                            const rowData = lines[i].split(/\s+/).filter(d => d);
                                            if (rowData.length === headers.length) {
                                                tableData.push(rowData);
                                            }
                                        }
                                        
                                        // 按Date-obs和Band排序
                                        sortTableData(headers);
                                        
                                        // 渲染表格
                                        renderDataTable(headers);
                                        noDataTable.style.display = 'none';
                                        dataTable.style.display = 'table';
                                    } else {
                                        throw new Error('Empty data file');
                                    }
                                })
                                .catch(error => {
                                    console.error('Error loading data file:', error);
                                    dataTable.innerHTML = '';
                                    dataTable.style.display = 'none';
                                    noDataTable.style.display = 'block';
                                    document.getElementById('downloadLink').style.display = 'none';
                                });
                        } else {
                            dataTable.innerHTML = '';
                            dataTable.style.display = 'none';
                            noDataTable.style.display = 'block';
                            document.getElementById('downloadLink').style.display = 'none';
                        }
                    })
                    .catch(error => {
                        console.error('Error loading target data:', error);
                        document.getElementById('noLightCurve').style.display = 'block';
                        document.getElementById('noIdentifyImages').style.display = 'block';
                        document.getElementById('noDataTable').style.display = 'block';
                        document.getElementById('downloadLink').style.display = 'none';
                    });
            }
            
            function sortTableData(headers) {
                // 找到Date-obs和Band列的索引
                const dateObsIndex = headers.findIndex(h => h.toLowerCase() === 'date-obs');
                const bandIndex = headers.findIndex(h => h.toLowerCase() === 'band');
                
                if (dateObsIndex === -1 || bandIndex === -1) {
                    // 如果没有找到这两列，不排序
                    sortedData = [...tableData];
                    return;
                }
                
                // 按Date-obs和Band排序
                sortedData = [...tableData].sort((a, b) => {
                    // 比较Date-obs
                    const dateA = a[dateObsIndex];
                    const dateB = b[dateObsIndex];
                    const dateCompare = dateA.localeCompare(dateB);
                    
                    if (dateCompare !== 0) {
                        return dateCompare;
                    }
                    
                    // 如果Date-obs相同，比较Band
                    const bandA = a[bandIndex];
                    const bandB = b[bandIndex];
                    return bandA.localeCompare(bandB);
                });
            }
            
            function groupBandImages(imageUrls) {
                const pairs = [];
                const bBandImages = imageUrls.filter(url => url.includes('_B_'));
                const rBandImages = imageUrls.filter(url => url.includes('_R_'));

                // 使用 Map 存储所有图像，键为 prefix+suffix
                const bMap = new Map();
                const rMap = new Map();

                bBandImages.forEach(bUrl => {
                    const [prefix, rest] = bUrl.split('_B_');
                    const suffix = rest.split('_').slice(1).join('_');
                    const key = `${prefix}___${suffix}`;
                    bMap.set(key, bUrl);
                });

                rBandImages.forEach(rUrl => {
                    const [prefix, rest] = rUrl.split('_R_');
                    const suffix = rest.split('_').slice(1).join('_');
                    const key = `${prefix}___${suffix}`;
                    rMap.set(key, rUrl);
                });

                // 合并键
                const allKeys = new Set([...bMap.keys(), ...rMap.keys()]);

                allKeys.forEach(key => {
                    const [prefix, suffix] = key.split('___');
                    pairs.push({
                        b: bMap.get(key) || null,
                        r: rMap.get(key) || null,
                        name: (bMap.get(key) || rMap.get(key)).split('/').pop().replace(/_[BR]_/, '_X_')
                    });
                });

                return pairs;
            }

            
            function updateBandImages() {
                if (imagePairs.length === 0) return;
                
                const pair = imagePairs[currentImageIndex];

                const bImg = document.getElementById('bBandImage');
                const rImg = document.getElementById('rBandImage');

                if (pair.b !== null) {
                    bImg.src = pair.b;
                }

                if (pair.r !== null) {
                    rImg.src = pair.r;
                }

                document.getElementById('imageCounter').textContent =
                    `${currentImageIndex + 1} / ${imagePairs.length} - ${pair.name}`;
            }
            
            function showNextImage() {
                if (imagePairs.length === 0) return;
                
                currentImageIndex = (currentImageIndex + 1) % imagePairs.length;
                updateBandImages();
                
                // 如果暂停状态，重新开始播放
                if (!isPlaying) {
                    togglePlayPause();
                }
            }
            
            function showPreviousImage() {
                if (imagePairs.length === 0) return;
                
                currentImageIndex = (currentImageIndex - 1 + imagePairs.length) % imagePairs.length;
                updateBandImages();
                
                // 如果暂停状态，重新开始播放
                if (!isPlaying) {
                    togglePlayPause();
                }
            }
            
            function togglePlayPause() {
                isPlaying = !isPlaying;
                document.getElementById('playPauseBtn').textContent = isPlaying ? 'Pause' : 'Play';
                
                if (isPlaying) {
                    startSlideshow();
                } else {
                    stopSlideshow();
                }
            }
            
            function startSlideshow() {
                stopSlideshow();
                slideshowInterval = setInterval(showNextImage, 2000); // 2秒切换一次
            }
            
            function stopSlideshow() {
                if (slideshowInterval) {
                    clearInterval(slideshowInterval);
                }
            }
            
            function renderDataTable(headers) {
                const dataTable = document.getElementById('dataTable');
                dataTable.innerHTML = '';
                
                // 创建表头
                const thead = document.createElement('thead');
                const headerRow = document.createElement('tr');
                
                headers.forEach(header => {
                    const th = document.createElement('th');
                    th.textContent = header;
                    headerRow.appendChild(th);
                });
                
                thead.appendChild(headerRow);
                dataTable.appendChild(thead);
                
                // 创建表体
                const tbody = document.createElement('tbody');
                dataTable.appendChild(tbody);
                
                // 渲染分页
                renderDataTablePage();
                
                // 显示分页控件
                const paginationControls = document.getElementById('paginationControls');
                if (sortedData.length > rowsPerPage) {
                    paginationControls.style.display = 'flex';
                } else {
                    paginationControls.style.display = 'none';
                }
            }
            
            function renderDataTablePage() {
                const tbody = document.querySelector('#dataTable tbody');
                tbody.innerHTML = '';
                
                const startIndex = (currentPage - 1) * rowsPerPage;
                const endIndex = Math.min(startIndex + rowsPerPage, sortedData.length);
                const totalPages = Math.ceil(sortedData.length / rowsPerPage);
                
                // 更新分页信息
                document.getElementById('pageInfo').textContent = `Page ${currentPage} of ${totalPages}`;
                
                // 渲染当前页的数据行
                for (let i = startIndex; i < endIndex; i++) {
                    const rowData = sortedData[i];
                    const row = document.createElement('tr');
                    
                    rowData.forEach(cellData => {
                        const td = document.createElement('td');
                        td.textContent = cellData;
                        row.appendChild(td);
                    });
                    
                    tbody.appendChild(row);
                }
                
                // 更新分页按钮状态
                document.getElementById('prevPageBtn').disabled = currentPage === 1;
                document.getElementById('nextPageBtn').disabled = currentPage === totalPages;
            }
        });
    </script>
</body>
</html>